import React from 'react';
import { connect } from 'react-redux';
import { Input, Button, List, message } from 'antd';
import { DeleteOutlined } from '@ant-design/icons';
import { getInputChangeAction, getAddItemAction, getDeleteItemAction, getSearchAction } from '../../reactReduxStore/actionCreators';
import axios from 'axios';

const TodoList = (props) => {
	const { inputValue, list, changeInputValue, handleKeyUpItemAdd, handleItemAdd, handleItemDelete, handleSearch } = props;
	return (
		<div className="todolist-page">
			<div>
				<Input
					className="todo-input"
					value={inputValue}
					onChange={changeInputValue}
					onKeyUp={(e) => handleKeyUpItemAdd(e, inputValue)}
				/>
				<Button type="primary" className="todo-btn" onClick={() => handleItemAdd(inputValue)}>提交</Button>
			</div>
			<div className="content">
				<List
					className="todo-list"
					bordered
					dataSource={list}
					renderItem={(item, index) => (
						<List.Item
							actions={
								[<DeleteOutlined 
									style={{ fontSize: '18px', color: '#f45656' }}
									onClick={() => handleItemDelete(index)}
								/>]
							}
						>
							{item}
						</List.Item>
					)}
				/>
				<Button type="primary" className="todo-btn" style={{marginTop: "10px"}} onClick={handleSearch}>查询</Button>
			</div>
		</div>
	)
}

// 把store的数据给这个组件，作为这个组件的props
const mapStateToProps = (state) => {
	return {
		inputValue: state.inputValue,
		list: state.list
	}
}

// store.dispatch方法挂载到props上，可以改变store里面的数据
const mapDispatchToProps = (dispatch) => {
	return {
		changeInputValue(e) {
			const action = getInputChangeAction(e.target.value);
			dispatch(action);
		},
		handleKeyUpItemAdd(e,inputValue) {
			if (e.keyCode === 13) {
				if (inputValue === '') {
					message.error('请输入内容');
					return;
				}
				const action = getAddItemAction();
				dispatch(action);
			}
		},
		handleItemAdd(inputValue) {
			if (inputValue === '') {
				message.error('请输入内容');
				return;
			}
			const action = getAddItemAction();
			dispatch(action);
		},
		handleItemDelete(index) {
			const action = getDeleteItemAction(index);
			dispatch(action);
		},
		handleSearch() {
			axios.get('/mocker/test.json').then(res => {
				const action = getSearchAction(res.data.list);
				dispatch(action);
			})
		}
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoList);